<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/java-notes/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/java-notes/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/java-notes/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/java-notes/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/java-notes/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/java-notes/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/java-notes/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Interview," />










<meta name="description" content="Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache and message broker.  Redis has built-in replication, Lua scripting, LRU eviction, transactions and d">
<meta property="og:type" content="article">
<meta property="og:title" content="Redis">
<meta property="og:url" content="https://hitomeng.gitee.io/2020/06/13/Redis/index.html">
<meta property="og:site_name" content="JavaNote">
<meta property="og:description" content="Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache and message broker.  Redis has built-in replication, Lua scripting, LRU eviction, transactions and d">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://hitomeng.gitee.io/java-notes/2020/06/13/Redis/redis-map-map.png">
<meta property="og:image" content="https://hitomeng.gitee.io/java-notes/2020/06/13/Redis/.%5CRedis%5Credis-map-map.png">
<meta property="og:image" content="https://hitomeng.gitee.io/java-notes/2020/06/13/Redis/.%5CRedis%5Credis-list.png">
<meta property="og:image" content="https://hitomeng.gitee.io/java-notes/2020/06/13/Redis/redis-list.png">
<meta property="og:image" content="https://hitomeng.gitee.io/java-notes/2020/06/13/Redis/E:%5Cbelogs%5CJavaNote%5Csource_posts%5CRedis%5Credis-set.png">
<meta property="og:image" content="https://hitomeng.gitee.io/java-notes/2020/06/13/Redis/redis-set.png">
<meta property="og:image" content="https://hitomeng.gitee.io/java-notes/2020/06/13/Redis/redis-zset.png">
<meta property="og:image" content="https://hitomeng.gitee.io/java-notes/2020/06/13/Redis/E:%5Cbelogs%5CJavaNote%5Csource_posts%5CRedis%5Credis-zset.png">
<meta property="article:published_time" content="2020-06-13T13:17:20.000Z">
<meta property="article:modified_time" content="2020-06-13T13:56:21.591Z">
<meta property="article:author" content="HitoMeng">
<meta property="article:tag" content="Interview">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://hitomeng.gitee.io/java-notes/2020/06/13/Redis/redis-map-map.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/java-notes/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://hitomeng.gitee.io/2020/06/13/Redis/"/>





  <title>Redis | JavaNote</title>
  








<meta name="generator" content="Hexo 4.2.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/java-notes/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">JavaNote</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">To be a better developer!</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/java-notes/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/java-notes/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/java-notes/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/java-notes/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/java-notes/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            About
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://hitomeng.gitee.io/java-notes/2020/06/13/Redis/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="HitoMeng">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/java-notes/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="JavaNote">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Redis</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2020-06-13T21:17:20+08:00">
                2020-06-13
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/java-notes/categories/database/" itemprop="url" rel="index">
                    <span itemprop="name">database</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <blockquote>
<p> Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache and message broker.  Redis has built-in replication, Lua scripting, LRU eviction, transactions and different levels of on-disk persistence, and provides high availability.</p>
</blockquote>
<a id="more"></a>

<h2 id="一、-基础"><a href="#一、-基础" class="headerlink" title="一、 基础"></a>一、 基础</h2><h4 id="为什么用Redis，而不是Map或Guava的Cache"><a href="#为什么用Redis，而不是Map或Guava的Cache" class="headerlink" title="为什么用Redis，而不是Map或Guava的Cache"></a>为什么用<strong>Redis</strong>，而不是Map或Guava的Cache</h4><ul>
<li>Redis可以做分布式缓存和远程缓存，满足高可用的需求，而Map只能缓存在本地，重启数据消失，Cache不能做到分布式</li>
<li>Redis有缓存过期机制，Map没有</li>
<li>Redis可多个服务器共享，但是Map不行</li>
</ul>
<h4 id="Redis原理"><a href="#Redis原理" class="headerlink" title="Redis原理"></a>Redis原理</h4><ol>
<li><p><strong>Redis为什么是单线程</strong>  </p>
<p>因为CPU不是Redis的瓶颈。Redis的瓶颈最有可能是机器内存或者网络带宽</p>
</li>
<li><p><strong>如果万一CPU成为你的Redis瓶颈了，或者，你就是不想让服务器其他核闲置，那怎么办</strong></p>
<p>那也很简单，你多起几个Redis进程就好了。Redis是keyvalue数据库，又不是关系数据库，数据之间没有约束。只要客户端分清哪些key放在哪个Redis进程上就可以了。redis-cluster可以帮你做的更好。 </p>
</li>
<li><p><strong>单线程模型</strong> </p>
<p>Redis客户端对服务端的每次调用都经历了发送命令，执行命令，返回结果三个过程。其中执行命令阶段，由于Redis是单线程来处理命令的，所有每一条到达服务端的命令不会立刻执行，所有的命令都会进入一个队列中，然后逐个被执行。并且多个客户端发送的命令的执行顺序是不确定的。但是可以确定的是不会有两条命令被同时执行，不会产生并发问题，这就是Redis的单线程基本模型。</p>
</li>
<li><p><strong>单线程模型每秒万级别处理能力的原因</strong> </p>
<ul>
<li>纯内存访问。 数据存放在内存中，内存的响应时间大约是 100纳秒 ，这是Redis每秒万亿级别访问的重要基础。</li>
<li>非阻塞I/O ，Redis采用<strong>epoll</strong>做为I/O多路复用技术的实现 ，再加上Redis自身的事件处理模型将epoll中的连接，读写，关闭都转换为了时间，不在I/O上浪费过多的时间。</li>
<li>单线程 避免了线程切换和竞态产生的消耗 。</li>
<li>Redis采用单线程模型，<strong>每条命令执行如果占用大量时间</strong>， 会造成其他线程阻塞，对于Redis这种高性能服务是致命的，所以Redis是面向高速执行的数据库。</li>
</ul>
</li>
</ol>
<h3 id="1-1-Redis的数据结构与应用场景"><a href="#1-1-Redis的数据结构与应用场景" class="headerlink" title="1.1 Redis的数据结构与应用场景"></a>1.1 Redis的数据结构与应用场景</h3><h4 id="String"><a href="#String" class="headerlink" title="String"></a>String</h4><p> 最基本的数据类型，一个key对应一个value . String类型是二进制安全的，意思是 redis 的 string 可以包含任何字符，不会像C语言中将\0作为字符的结束判断。</p>
<p>1.缓存： 经典使用场景，把常用信息，字符串，图片或者视频等信息放到redis中，redis作为缓存层，mysql做持久化层，降低MySQL的读写压力。</p>
<p>2.计数器：redis是单线程模型，一个命令执行完才会执行下一个，同时数据可以一步落地到其他的数据源。</p>
<p>3.session：常见方案spring session + redis实现session共享 </p>
<h4 id="Hash"><a href="#Hash" class="headerlink" title="Hash"></a>Hash</h4><p> 一个Mapmap，指值本身又是一种键值对结构</p>
<img src="/java-notes/2020/06/13/Redis/redis-map-map.png" class title="b-tree">

<p><img src="/java-notes/2020/06/13/Redis/.%5CRedis%5Credis-map-map.png" alt="Hash结构"></p>
<p>场景： 缓存，能直观，相比string更节省空间的维护缓存信息，如用户信息，视频信息等 </p>
<h4 id="List-链表"><a href="#List-链表" class="headerlink" title="List 链表"></a>List 链表</h4><p> redis 使用双端链表实现List， 左右两边都能进行插入和删除数据 ，配合不同的操作可是实现不同的数据结构。</p>
<ul>
<li><p>lpush+lpop=Stack(栈)</p>
</li>
<li><p>lpush+rpop=Queue（队列）</p>
</li>
<li><p>lpush+ltrim=Capped Collection（有限集合）</p>
</li>
<li><p>lpush+brpop（阻塞操作）=Message Queue（消息队列）</p>
<p><img src="/java-notes/2020/06/13/Redis/.%5CRedis%5Credis-list.png" alt="img"></p>
<img src="/java-notes/2020/06/13/Redis/redis-list.png" class title="redis-list">  

</li>
</ul>
<h4 id="Set-集合"><a href="#Set-集合" class="headerlink" title="Set 集合"></a>Set 集合</h4><p>无序不重复的字符串列表。</p>
<ol>
<li><p>不允许有重复的元素，</p>
</li>
<li><p>集合中的元素是无序的，不能通过索引下标获取元素，</p>
</li>
<li><p>支持集合间的操作，可以取多个集合取交集、并集、差集。 </p>
<p><img src="/java-notes/2020/06/13/Redis/E:%5Cbelogs%5CJavaNote%5Csource_posts%5CRedis%5Credis-set.png" alt="img"></p>
<img src="/java-notes/2020/06/13/Redis/redis-set.png" class title="redis-set">  

</li>
</ol>
<p>应用：标签集合。一个用户的多种标签，协同过滤</p>
<h4 id="ZSet-有序集合"><a href="#ZSet-有序集合" class="headerlink" title="ZSet 有序集合"></a>ZSet 有序集合</h4><p>在Set的基础之上，加入了<strong>有序</strong>功能，排序根据得分（手动设置）</p>
 <img src="/java-notes/2020/06/13/Redis/redis-zset.png" class title="redis-zset"> 

<p> <img src="/java-notes/2020/06/13/Redis/E:%5Cbelogs%5CJavaNote%5Csource_posts%5CRedis%5Credis-zset.png" alt="img"> </p>
<p>应用：排行榜。</p>
<p> <a href="https://juejin.im/post/5db69365518825645656c0de" target="_blank" rel="noopener">避免缓存击穿的利器之BloomFilter</a> </p>
<h2 id="二、进阶"><a href="#二、进阶" class="headerlink" title="二、进阶"></a>二、进阶</h2><h4 id="如果有大量的key需要设置同一时间过期（缓存雪崩），一般需要注意什么？"><a href="#如果有大量的key需要设置同一时间过期（缓存雪崩），一般需要注意什么？" class="headerlink" title="如果有大量的key需要设置同一时间过期（缓存雪崩），一般需要注意什么？"></a>如果有大量的key需要设置同一时间过期（缓存雪崩），一般需要注意什么？</h4><p> 如果大量的key过期时间设置的过于集中，到过期的那个时间点，<strong>Redis</strong>可能会出现短暂的卡顿现象。严重的话会<br>出现缓存雪崩，我们一般需要在时间上加一个随机值，使得过期时间分散一些。 </p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">setRedis（Key，value，time + Math.random() * 10000）</span><br></pre></td></tr></table></figure>



<h4 id="Redis分布式锁"><a href="#Redis分布式锁" class="headerlink" title="Redis分布式锁"></a>Redis分布式锁</h4><p> 拿<strong>setnx</strong>来争抢锁，抢到之后，再用<strong>expire</strong>给锁加一个过期时间防止锁忘记了释放。 </p>
<p>如果在setnx之后执行expire之前进程意外crash或者要重启维护了，那会怎么样? 同时把<strong>setnx</strong>和<strong>expire</strong>合成一条指令 。其实自己实现分布式锁很容易出现问题的，市场上有很多开源实现，如Redisson.可以保证获取锁的客户端保证完成业务逻辑后再释放锁，通过WathcDog。而且支持分布式Redis集群模式，但是由于主从同步问题可能导致锁数据同步失败，可以考虑用Redis自带的Redlock算法提高可用率。</p>
<h4 id="Redis里面有1亿个key，其中有10w个key是以某个固定的已知的前缀开头的，如何将它们全部找出来"><a href="#Redis里面有1亿个key，其中有10w个key是以某个固定的已知的前缀开头的，如何将它们全部找出来" class="headerlink" title="Redis里面有1亿个key，其中有10w个key是以某个固定的已知的前缀开头的，如何将它们全部找出来"></a>Redis里面有1亿个key，其中有10w个key是以某个固定的已知的前缀开头的，如何将它们全部找出来</h4><p> 使用<strong>keys</strong>指令可以扫出指定模式的key列表 。这个redis正在给线上的业务提供服务，那使用keys指令会有什么问题？Redis的单线程的。keys指令会导致线程阻塞一段时间，线上服务会停顿，直到指令执行完毕，服务才能恢复。这个时候可以使用<strong>scan</strong>指令，<strong>scan</strong>指令可以无阻塞的提取出指定模式的key列表，但是会有一定的重复概率，在客户端做一次去重就可以了，但是整体所花费的时间会比直接用keys指令长.</p>
<h4 id="使用过Redis做异步队列么，你是怎么用的"><a href="#使用过Redis做异步队列么，你是怎么用的" class="headerlink" title="使用过Redis做异步队列么，你是怎么用的"></a>使用过Redis做异步队列么，你是怎么用的</h4><p> 一般使用list结构作为队列，<strong>rpush</strong>生产消息，<strong>lpop</strong>消费消息。当lpop没有消息的时候，要适当sleep一会再重试。 </p>
<h4 id="Redis是怎么持久化的？"><a href="#Redis是怎么持久化的？" class="headerlink" title="Redis是怎么持久化的？"></a>Redis是怎么持久化的？</h4><p>RDB做镜像全量持久化，AOF做增量持久化。因为RDB会耗费较长时间，不够实时，在停机的时候会导致大量丢失数据，所以需要AOF来配合使用。在redis实例重启时，会使用RDB持久化文件重新构建内存，再使用AOF重放近期的操作指令来实现完整恢复重启之前的状态。</p>
<p>RDB: 生成多个数据文件，每个数据文件分别都代表了某一时刻<strong>Redis</strong>里面的数据M适合做<strong>冷备</strong>，完整的数据运维设置定时任务，定时同步到远端的服务器. <strong>RDB</strong>对<strong>Redis</strong>的<strong>性能</strong>影响非常小，是因为在同步数据的时候他只是<strong>fork</strong>了一个子进程去做持久化的，而且他在数据恢复的时候速度比<strong>AOF</strong>来的快。RDB都是快照文件，都是默认五分钟甚至更久的时间才会生成一次，AOF是秒级别的，数据完整性差。</p>
<p>AOF: <strong>AOF</strong>是一秒一次去通过一个后台的线程<code>fsync</code><strong>记录操作</strong>，那最多丢这一秒的数据。  <strong>AOF</strong>在对日志文件进行操作的时候是以<code>append-only</code>的方式去写的，日志文件写入快速。 一样的数据，<strong>AOF</strong>文件比<strong>RDB</strong>还要大。 </p>
<h4 id="Redis的同步机制，服务主从数据怎么交互的？"><a href="#Redis的同步机制，服务主从数据怎么交互的？" class="headerlink" title="Redis的同步机制，服务主从数据怎么交互的？"></a>Redis的同步机制，服务主从数据怎么交互的？</h4><p>Redis可以使用主从同步，从从同步。第一次同步时，主节点做一次<strong>bgsave</strong>，并同时将后续修改操作记录到内存buffer，待完成后将RDB文件全量同步到复制节点，复制节点接受完成后将RDB镜像加载到内存。加载完成后，再通知主节点将期间修改的操作记录同步到复制节点进行重放就完成了同步过程。后续的增量数据通过AOF日志同步即可。</p>
<h4 id="是否使用过Redis集群，集群的高可用怎么保证，集群的原理是什么"><a href="#是否使用过Redis集群，集群的高可用怎么保证，集群的原理是什么" class="headerlink" title="是否使用过Redis集群，集群的高可用怎么保证，集群的原理是什么"></a>是否使用过Redis集群，集群的高可用怎么保证，集群的原理是什么</h4><p><strong>Redis Cluster</strong> 着眼于扩展性，在单个redis内存不足时，使用Cluster进行分片存储。 Master是主，Slave是从，Master具有读写权限，Slave只有读权限 ，提高访问性能。</p>
<p><strong>Redis Sentinal</strong> 哨兵模式。在集群的基础上多引入若干个哨兵节点，哨兵监控Master可用性，Master失效则从Slave中重新选举出新的Master。着眼于高可用，在master宕机时会自动将slave提升为master，继续提供服务。</p>
<p>集群监控：负责监控 Redis master 和 slave 进程是否正常工作。</p>
<p>消息通知：如果某个 <strong>Redis</strong> 实例有故障，那么哨兵负责发送消息作为报警通知给管理员。</p>
<p>故障转移：如果 master node 挂掉了，会自动转移到 slave node 上。</p>
<p>配置中心：如果故障转移发生了，通知 client 客户端新的 master 地址。</p>
<h4 id="那你了解缓存穿透和击穿么，可以说说他们跟雪崩的区别么"><a href="#那你了解缓存穿透和击穿么，可以说说他们跟雪崩的区别么" class="headerlink" title="那你了解缓存穿透和击穿么，可以说说他们跟雪崩的区别么"></a>那你了解缓存穿透和击穿么，可以说说他们跟雪崩的区别么</h4><ol>
<li>缓存击穿：强调的是一点点某个点的击穿这一动作。某个Key对于的热点数据，频繁被访问，然后这个Key突然过期，然后导致请求全部落到数据库。雪崩指的是某一时刻大量的热点数据同时失效。 设置热点数据永远不过期，或者牺牲性能加上互斥锁。</li>
<li>缓存穿透：每次请求的数据都不在Redis缓存中，需要直接访问MySQL。如使用恶意不存的用户ID访问某接口。处理：接口校验。<a href="https://juejin.im/post/5db69365518825645656c0de" target="_blank" rel="noopener">避免缓存击穿的利器之BloomFilter</a> 。</li>
</ol>
<h4 id="Redis的过期策略和内存淘汰机制"><a href="#Redis的过期策略和内存淘汰机制" class="headerlink" title="Redis的过期策略和内存淘汰机制"></a>Redis的过期策略和内存淘汰机制</h4><p><strong>过期策略</strong>: 定期删除+惰性删除。</p>
<p>定期删除，指的是redis默认是每隔100ms就随机抽取一些设置了过期时间的key，检查其是否过期，如果过期就删除。注意，这里可不是每隔100ms就遍历所有的设置过期时间的key，那样就是一场性能上的灾难。实际上redis是每隔100ms随机抽取一些key来检查和删除的。</p>
<p> <strong>惰性删除：</strong> 在你获取某个key的时候，redis会检查一下 ，这个key如果设置了过期时间那么是否过期了？如果过期了此时就会删除，不会给你返回任何东西。 </p>
<p> redis的内存占用过多的时候，此时会进行内存淘汰 ：</p>
<p>noeviction：当内存不足以容纳新写入数据时，新写入操作会报错，这个一般没人用吧</p>
<p><strong>allkeys-lru：当内存不足以容纳新写入数据时，在键空间中，移除最近最少使用的key（这个是最常用的）</strong></p>
<p>allkeys-random：当内存不足以容纳新写入数据时，在键空间中，随机移除某个key，这个一般没人用吧</p>
<p>volatile-lru：当内存不足以容纳新写入数据时，在设置了过期时间的键空间中，移除最近最少使用的key（这个一般不太合适）</p>
<p>volatile-random：当内存不足以容纳新写入数据时，在设置了过期时间的键空间中，随机移除某个key</p>
<p>volatile-ttl：当内存不足以容纳新写入数据时，在设置了过期时间的键空间中，有更早过期时间的key优先移除</p>
<h4 id="手写LRU算法"><a href="#手写LRU算法" class="headerlink" title="手写LRU算法"></a>手写LRU算法</h4><ol>
<li>基于LinkedHashMap实现.构造函数的第三个参数设为True，重写removeEldestEntry方法，满了返回True。</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">final</span> <span class="keyword">int</span> cacheSize = <span class="number">100</span>;</span><br><span class="line">Map&lt;String, String&gt; map = <span class="keyword">new</span> LinkedHashMap&lt;String, String&gt;((<span class="keyword">int</span>) Math.ceil(cacheSize / <span class="number">0.75f</span>) + <span class="number">1</span>, <span class="number">0.75f</span>, <span class="keyword">true</span>) &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">boolean</span> <span class="title">removeEldestEntry</span><span class="params">(Map.Entry&lt;String, String&gt; eldest)</span> </span>&#123;</span><br><span class="line">    	<span class="keyword">return</span> size() &gt; cacheSize;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<ol start="2">
<li><p>手动用过 双向链表加HashMap实现 <a href="https://leetcode-cn.com/problems/lru-cache/" target="_blank" rel="noopener">146. LRU缓存机制</a></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">LRUCache</span> </span>&#123;</span><br><span class="line">  <span class="keyword">private</span> <span class="keyword">int</span> capacity;</span><br><span class="line">    <span class="keyword">private</span> HashMap&lt;Integer, Node&gt; cache;</span><br><span class="line">    <span class="keyword">private</span> DoubleList doubleList;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">LRUCache</span><span class="params">(<span class="keyword">int</span> capacity)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 1. 初始化双向链表和HashMap</span></span><br><span class="line">        cache = <span class="keyword">new</span> HashMap&lt;&gt;(capacity);</span><br><span class="line">        doubleList = <span class="keyword">new</span> DoubleList();</span><br><span class="line">        <span class="keyword">this</span>.capacity = capacity;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">get</span><span class="params">(<span class="keyword">int</span> key)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 存在，返回并将Node移动到链表头</span></span><br><span class="line">        <span class="comment">// 不存在，返回-1</span></span><br><span class="line">        <span class="keyword">int</span> value = -<span class="number">1</span>;</span><br><span class="line">        <span class="keyword">if</span> (cache.keySet().contains(key)) &#123;</span><br><span class="line">            Node node = cache.get(key);</span><br><span class="line">            doubleList.moveToHead(node);</span><br><span class="line">            value = node.val;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> value;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">put</span><span class="params">(<span class="keyword">int</span> key, <span class="keyword">int</span> value)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 存在更新值，不存在判断是否能添加</span></span><br><span class="line">        Node old = cache.get(key);</span><br><span class="line">        <span class="keyword">if</span> (old == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="comment">// 满了，删除最后一个，没满，添加到头</span></span><br><span class="line">            Node newNode = <span class="keyword">new</span> Node(key, value);</span><br><span class="line">            <span class="keyword">if</span> (doubleList.size() == capacity) &#123;</span><br><span class="line">                Node last = doubleList.removeLast();</span><br><span class="line">                cache.remove(last.key);</span><br><span class="line">            &#125;</span><br><span class="line">            cache.put(key, newNode);</span><br><span class="line">            doubleList.add(newNode);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            old.val = value;</span><br><span class="line">            doubleList.moveToHead(old);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 双向链表，remove addFirst removeLast</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DoubleList</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 引入头尾结点同意操作</span></span><br><span class="line">        <span class="keyword">private</span> Node head;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">private</span> Node tail;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">private</span> <span class="keyword">int</span> size = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="title">DoubleList</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            head = <span class="keyword">new</span> Node(<span class="number">0</span>, <span class="number">0</span>);</span><br><span class="line">            tail = <span class="keyword">new</span> Node(<span class="number">0</span>, <span class="number">0</span>);</span><br><span class="line">            head.next = tail;</span><br><span class="line">            head.pre = tail;</span><br><span class="line">            tail.next = head;</span><br><span class="line">            tail.pre = head;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// head tail 是手动加的，默认不会删除</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">remove</span><span class="params">(Node node)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">if</span> (isEmpty()) &#123;</span><br><span class="line">                <span class="keyword">return</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            node.pre.next = node.next;</span><br><span class="line">            node.next.pre = node.pre;</span><br><span class="line">            size -= <span class="number">1</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 新增结点放在头部</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">add</span><span class="params">(Node node)</span> </span>&#123;</span><br><span class="line">            head.next.pre = node;</span><br><span class="line">            node.next = head.next;</span><br><span class="line">            head.next = node;</span><br><span class="line">            node.pre = head;</span><br><span class="line">            size += <span class="number">1</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">moveToHead</span><span class="params">(Node node)</span> </span>&#123;</span><br><span class="line">            remove(node);</span><br><span class="line">            add(node);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">public</span> Node <span class="title">removeLast</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            <span class="keyword">if</span> (isEmpty()) &#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            Node temp = tail.pre;</span><br><span class="line">            remove(temp);</span><br><span class="line">            <span class="keyword">return</span> temp;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">size</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            <span class="keyword">return</span> size;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isEmpty</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            <span class="keyword">return</span> size == <span class="number">0</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 双向链表中的结点定义</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Node</span> </span>&#123;</span><br><span class="line">        <span class="keyword">public</span> <span class="keyword">int</span> key;</span><br><span class="line">        <span class="keyword">public</span> <span class="keyword">int</span> val;</span><br><span class="line">        <span class="keyword">public</span> Node next;</span><br><span class="line">        <span class="keyword">public</span> Node pre;</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="title">Node</span><span class="params">(<span class="keyword">int</span> key, <span class="keyword">int</span> val)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">this</span>.key = key;</span><br><span class="line">            <span class="keyword">this</span>.val = val;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ol>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/java-notes/tags/Interview/" rel="tag"># Interview</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/java-notes/2020/05/25/JavaSe%E5%B8%B8%E8%A7%81%E9%9D%A2%E8%AF%95/" rel="next" title="JavaSe常见面试">
                <i class="fa fa-chevron-left"></i> JavaSe常见面试
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">HitoMeng</p>
              <p class="site-description motion-element" itemprop="description">You do have the time!</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/java-notes/archives/%7C%7Carchive">
              
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/java-notes/categories/index.html">
                  <span class="site-state-item-count">3</span>
                  <span class="site-state-item-name">categories</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/java-notes/tags/index.html">
                  <span class="site-state-item-count">8</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#一、-基础"><span class="nav-number">1.</span> <span class="nav-text">一、 基础</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#为什么用Redis，而不是Map或Guava的Cache"><span class="nav-number">1.0.1.</span> <span class="nav-text">为什么用Redis，而不是Map或Guava的Cache</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Redis原理"><span class="nav-number">1.0.2.</span> <span class="nav-text">Redis原理</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-1-Redis的数据结构与应用场景"><span class="nav-number">1.1.</span> <span class="nav-text">1.1 Redis的数据结构与应用场景</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#String"><span class="nav-number">1.1.1.</span> <span class="nav-text">String</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Hash"><span class="nav-number">1.1.2.</span> <span class="nav-text">Hash</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#List-链表"><span class="nav-number">1.1.3.</span> <span class="nav-text">List 链表</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Set-集合"><span class="nav-number">1.1.4.</span> <span class="nav-text">Set 集合</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#ZSet-有序集合"><span class="nav-number">1.1.5.</span> <span class="nav-text">ZSet 有序集合</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二、进阶"><span class="nav-number">2.</span> <span class="nav-text">二、进阶</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#如果有大量的key需要设置同一时间过期（缓存雪崩），一般需要注意什么？"><span class="nav-number">2.0.1.</span> <span class="nav-text">如果有大量的key需要设置同一时间过期（缓存雪崩），一般需要注意什么？</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Redis分布式锁"><span class="nav-number">2.0.2.</span> <span class="nav-text">Redis分布式锁</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Redis里面有1亿个key，其中有10w个key是以某个固定的已知的前缀开头的，如何将它们全部找出来"><span class="nav-number">2.0.3.</span> <span class="nav-text">Redis里面有1亿个key，其中有10w个key是以某个固定的已知的前缀开头的，如何将它们全部找出来</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#使用过Redis做异步队列么，你是怎么用的"><span class="nav-number">2.0.4.</span> <span class="nav-text">使用过Redis做异步队列么，你是怎么用的</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Redis是怎么持久化的？"><span class="nav-number">2.0.5.</span> <span class="nav-text">Redis是怎么持久化的？</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Redis的同步机制，服务主从数据怎么交互的？"><span class="nav-number">2.0.6.</span> <span class="nav-text">Redis的同步机制，服务主从数据怎么交互的？</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#是否使用过Redis集群，集群的高可用怎么保证，集群的原理是什么"><span class="nav-number">2.0.7.</span> <span class="nav-text">是否使用过Redis集群，集群的高可用怎么保证，集群的原理是什么</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#那你了解缓存穿透和击穿么，可以说说他们跟雪崩的区别么"><span class="nav-number">2.0.8.</span> <span class="nav-text">那你了解缓存穿透和击穿么，可以说说他们跟雪崩的区别么</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Redis的过期策略和内存淘汰机制"><span class="nav-number">2.0.9.</span> <span class="nav-text">Redis的过期策略和内存淘汰机制</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#手写LRU算法"><span class="nav-number">2.0.10.</span> <span class="nav-text">手写LRU算法</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">HitoMeng</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/java-notes/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/java-notes/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/java-notes/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/java-notes/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/java-notes/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/java-notes/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/java-notes/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/java-notes/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/java-notes/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/java-notes/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/java-notes/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/java-notes/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/java-notes/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
